package com.tss.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tss.mapper.ApplyMapper;
import com.tss.mapper.CourseMapper;
import com.tss.mapper.StudentMapper;
import com.tss.pojo.Apply;
import com.tss.pojo.ApplyExample;
import com.tss.pojo.ApplyExample.Criteria;
import com.tss.pojo.ApplyResult;
import com.tss.pojo.Course;
import com.tss.pojo.Result;
import com.tss.pojo.Student;
import com.tss.service.ApplyService;
import com.tss.utils.BeanUtils;
import com.tss.vo.Dictionary;

@Service
public class ApplyServiceImpl implements ApplyService {

	@Autowired
	private ApplyMapper applyMapper;
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private StudentMapper studentMapper;
	
	/**
	 * 根据状态列出申请
	 */
	@Override
	public List<ApplyResult> list(Long status) {
		ApplyExample example = new ApplyExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		if(status!=null){
			criteria.andStatusEqualTo(status);
		}
		
		List<Apply> list = applyMapper.selectByExample(example);
		if(list==null){
			return null;
		}
		List<ApplyResult> applyResultList = new ArrayList<ApplyResult>();
		for(Apply apply:list){
			ApplyResult applyResult = new ApplyResult();
			applyResult.setId(apply.getId());
			Course course = courseMapper.selectByPrimaryKey(apply.getCourseId());
			Student student = studentMapper.selectByPrimaryKey(apply.getStudentId());
			if(course==null||student==null){
				continue;
			}
			applyResult.setCoursepName(course.getName());
			applyResult.setStudentName(student.getRealName());
			applyResultList.add(applyResult);
		}
		
		return applyResultList;
	}
	
	@Override
	public Result updateApply(Apply apply) {
		Result result = new Result();
		Apply a = applyMapper.selectByPrimaryKey(apply.getId());
		a=BeanUtils.updateBean(a, apply);
		applyMapper.updateByPrimaryKey(a);
		result.setSuccessMessage("审核成功！");
		return result;
	}

	@Override
	public Result addApply(Apply apply) {
		Result result = new Result();
		if(apply==null||apply.getCourseId()==null||apply.getStudentId()==null){
			result.setErrorMessage("参数错误！");
			return result;
		}
		if(findApply(apply)!=null){
			result.setErrorMessage("请勿重复报名！");
			return result;
		}
		apply.setValidate(true);
		apply.setStatus(0L);
		applyMapper.insert(apply);
		result.setSuccessMessage("报名成功！");
		return result;
	}

	@Override
	public Apply findApply(Apply apply) {
		if(apply==null){
			return null;
		}
		
		if(apply.getId()!=null){
			Apply a = applyMapper.selectByPrimaryKey(apply.getId());
			if(a.getValidate()==true){
				return a;
			}else{
				return null;
			}
		}
		ApplyExample example = new ApplyExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		criteria.andCourseIdEqualTo(apply.getCourseId());
		criteria.andStudentIdEqualTo(apply.getStudentId());
		List<Apply> list = applyMapper.selectByExample(example);
		if(!list.isEmpty()){
			return list.get(0);
		}
		return null;
	}
	
	@Override
	public Result deleteApply(Apply apply){
		Result result = new Result();
		if(apply==null){
			result.setErrorMessage("参数错误！");
			return result;
		}
		Apply a = findApply(apply);
		if(a == null){
			result.setErrorMessage("删除失败！");
			return result;
		}
		a.setValidate(false);
		applyMapper.updateByPrimaryKey(a);
		result.setSuccessMessage("删除成功！");
		return result;
	}

	@Override
	public List<Course> listCourse(Student s) {
		if(s==null||s.getId()==null){
			return null;
		}
		ApplyExample example = new ApplyExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		criteria.andStudentIdEqualTo(s.getId());
		criteria.andStatusEqualTo(Dictionary.APPLY_STATUS_PASSED);
		List<Apply> list = applyMapper.selectByExample(example);
		if(list.isEmpty()){
			return null;
		}
		List<Course> courseList = new ArrayList<Course>();
		for(Apply apply:list){
			
			Course course = courseMapper.selectByPrimaryKey(apply.getCourseId());
			if(course==null){
				continue;
			}
			courseList.add(course);
		}
		return courseList;
	}

	@Override
	public Long countApply(Long courseId) {
		if(courseId==null){
			return 0L;
		}
		ApplyExample example = new ApplyExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		criteria.andCourseIdEqualTo(courseId);
		return (long) applyMapper.countByExample(example);
	}

	@Override
	public List<Apply> listApply(Long courseId) {
		ApplyExample example = new ApplyExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		criteria.andStatusEqualTo(Dictionary.APPLY_STATUS_PASSED);
		criteria.andCourseIdEqualTo(courseId);
		List<Apply> list = applyMapper.selectByExample(example);
		if(list.isEmpty()){
			return null;
		}
		return list;
	}

	@Override
	public Result importApply(File file) {
		Result result = new Result();
		
		String excelFile = uploadExcel(file);

		//解析Excel文件
		Map data = new HashMap();
/*		try {
			data = SigninExcelHandler.readExcel(excelFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//依次将data中的数据映射到Signind对象并保存到数据库
		Set<Object> keySet = data.keySet();
        for(Object obj:keySet){
        	ArrayList<Signin> signins = new ArrayList<Signin>();
        	signins = (ArrayList<Signin>) data.get(obj);
        	
        	for(Signin signin:signins){
        		
    			signin.setIsSignin("0");
    			signin.setStatus("SIGNIN_NORMAL");
    			signin.setIsPrint("0");
    			signin.setIsSave("0");
    			
        		try {
        			this.signinDao.save(signin);
				} catch (Exception e) {
					e.printStackTrace();
				}
        		
        	}
        }*/
		
		return null;
	}
	
	//上传Excel文件并返回文件保存在服务器上的全路径
		public String uploadExcel(File file){
			String fileName=(new StringBuffer(String.valueOf(getRandomNum()))).append(".")
					.append("xls").toString();

			/*String realpath = ServletActionContext.getServletContext().getRealPath("/upload/enterprice/files");
			
	        if (file != null) {
	            File savefile = new File(new File(realpath), fileName);
	            if (!savefile.getParentFile().exists())
	                savefile.getParentFile().mkdirs();
	            
				try {
					FileUtils.copyFile(file, savefile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
	            System.out.println("文件上传成功");
	            return savefile.getAbsolutePath();
	        }*/
	        
	        return null;
		}
		
		public String getRandomNum() {
			Calendar cal = Calendar.getInstance();
			Integer year = Integer.valueOf(cal.get(Calendar.YEAR));
			Integer day = Integer.valueOf(cal.get(Calendar.DAY_OF_MONTH));
			Integer month = Integer.valueOf(cal.get(Calendar.MONTH) + 1);
			Integer hour = Integer.valueOf(cal.get(Calendar.HOUR_OF_DAY));
			Integer minute = Integer.valueOf(cal.get(Calendar.MINUTE));
			
			String strTime = year.toString() + month.toString() + day.toString() + hour.toString() + minute.toString();
			String strRan = strTime + String.valueOf(Math.round(Math.random() * 8999 + 1000));
			return strRan;
		}
	
	
	


}
